package com.zh.note.demo.java8;

import java.util.*;
import java.util.stream.Collectors;

/**
 * list去重
 */
public class ListRemoveDuplicates {

    public static void main(String[] args) {


//        m1();
//        m2();
        m3();
        m4();

    }

    /**
     * for循环
     */
    private static void m1() {
        List<Integer> initList = Arrays.asList(70, 70, -1, 5, 3, 3, 4, 4, 4, 4, 99);
        List<Integer> srcList = new ArrayList<>(initList);
        List<Integer> newList = new ArrayList<>();

        for (int i = 0; i < srcList.size(); i++) {
            Integer temp = srcList.get(i);
            if (!newList.contains(temp)) {
                newList.add(temp);
            }
        }
        System.out.println(newList);

    }

    /**
     * hashSet 或者LinkedHashSet去重
     */
    private static void m2() {
        List<Integer> initList = Arrays.asList(70, 70, -1, 5, 3, 3, 4, 4, 4, 4, 99);
        List<Integer> srcList = new ArrayList<>(new HashSet<>(initList));
        System.out.println(srcList);
        List<Integer> srcList1 = new ArrayList<>(new LinkedHashSet<>(initList));
        System.out.println(srcList1);

    }

    /**
     * steam流
     */
    private static void m3() {
        List<Integer> initList = Arrays.asList(70, 70, -1, 5, 3, 3, 4, 4, 4, 4, 99);
        List<Integer> newList = new ArrayList<>(initList).stream().distinct().collect(Collectors.toList());
        System.out.println(newList);
    }

    /**
     * 算法思想：前后双指针
     */
    private static void m4() {

        List<Integer> initList = Arrays.asList(70, 70, -1, 5, 3, 3, 4, 4, 4, 4, 99);
        List<Integer> srcList = new ArrayList<>(initList);
        List<Integer> newList = new ArrayList<>(initList);

        for (Integer element : srcList) {

            if (newList.indexOf(element) != newList.lastIndexOf(element)) {
                newList.remove(newList.indexOf(element));
            }
        }

        System.out.println(newList);

    }
}
